package com.bwie.service.impl;

import cn.hutool.captcha.generator.RandomGenerator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.domain.Bo;
import com.bwie.domain.Plan;
import com.bwie.mapper.BoMapper;
import com.bwie.mapper.PlanMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.UserMapper;
import com.bwie.domain.User;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BoMapper boMapper;

    @Autowired
    private PlanMapper planMapper;
    @Override
    public R login(LoginVo loginVo) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,loginVo.getUsername());
        User one = userMapper.selectOne(wrapper);
        if(one==null){
            return R.ERROR(404,"系统中没有该账号");
        }

        if(!one.getPassword().equals(loginVo.getPassword())){
            return R.ERROR(404,"密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", one.getUserId()).compact();
        redisTemplate.opsForValue().set("token:",token,30, TimeUnit.MINUTES);
        one.setToken(token);
        return R.OK(one);
    }

    @Override
    public R getBoList() {
        List<Bo> bos = boMapper.selectList(null);
        return R.OK(bos);
    }

    @Override
    public R getPlanList() {
        List<Plan> plans = planMapper.selectList(null);
        return R.OK(plans);
    }

    @Override
    public R addPlan(Plan plan) {
        planMapper.insert(plan);
        return R.OK();
    }
}
